var createError = require("http-errors");
var express = require("express");
const { expressjwt: expressJwt } = require("express-jwt");
const cors = require("cors");
const fs = require("fs");
var path = require("path");
var cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const configs = require("./config");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var loginRouter = require("./routes/login");
var logRouter = require("./routes/log");
var uploadRouter = require("./routes/upload");
var app = express();

app.use(cors());
app.use(
  expressJwt({
    secret: configs.token.SECRET_KEY,
    algorithms: ["HS256"],
  }).unless({ path: [/^\/login\//] })
);

// 视图引擎设置
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

// 日志中间件
const logger = require("./utils/logger");
app.use(logger.accessLog);
app.use(logger.accessLogErr);
app.use(logger.logger("dev"));

// 解析请求体
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.json());

// 静态文件中间件
app.use(express.static(path.join(__dirname, "public")));

// 路由
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/log", logRouter);
app.use("/login", loginRouter);
app.use("/upload", uploadRouter);

// 错误处理中间件
app.use(function (err, req, res, next) {
  if (err.status === 404) {
    return res.status(404).send("Not Found");
  }
  if (err.name === 'UnauthorizedError' && err.message === 'invalid token') {
    return res.status(403).send({code:403,message:'无效的token'});
  }
  if (err.name === 'UnauthorizedError' && err.message === 'jwt expired') {
    return res.status(401).send({code:401,message:'token过期'});
  }
  res.status(err.status || 500).send({code:err.status || 500,message:err.message});
});

module.exports = app;